﻿//------------------------------------------------------------------------------
// The contents of this file are subject to the Microsoft Public License (Ms-PL)
// You may obtain a copy of the License at http://psadmin.codeplex.com/license. 
// 
// Software distributed under the License is distributed on an "AS IS" basis, 
// WITHOUT WARRANTY OF ANY KIND, either express or implied. 
// See the License for the specific language governing rights and limitations 
// under the License.
// 
// The initial developer is Ben Foster (ben.foster@retroviz.com)
// Copyright (c) Retroviz Limited (http://www.retroviz.com).
// All Rights Reserved.
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PSAdmin.Core.Interfaces;
using NVelocity;
using NVelocity.App;
using System.IO;

namespace PSAdmin.Services
{
    public class NVelocityTemplateService : ITemplateService
    {
        public string ProcessTemplate(string templateContent, IDictionary<string, object> data)
        {
            if (string.IsNullOrEmpty(templateContent))
                throw new ArgumentException("Template content cannot be null", "templateContent");

            var engine = new VelocityEngine();
            engine.Init();
            var context = GetContext(data);
            using (var writer = new StringWriter()) {
                engine.Evaluate(context, writer, "", templateContent);
                return writer.GetStringBuilder().ToString();
            }
        }

        private VelocityContext GetContext(IDictionary<string, object> data) {
            var context = new VelocityContext();
            var templateData = data ?? new Dictionary<string, object>();
            foreach (var key in templateData.Keys) {
                context.Put(key, templateData[key]);
            }
            return context;
        }
        
    }
}
